package app.caihan.scframe.api.retrofit2

import com.blankj.utilcode.util.Utils
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.OkHttpClient
import retrofit2.Retrofit


/**
 * Retrofit基类
 *
 * @author Seven-C
 * @date 2020/8/10
 */
abstract class BaseRetrofitClient {

    companion object {
        const val CONNECT_TIME_OUT = 10L
        const val WRITE_TIME_OUT = 10L
        const val CALL_TIME_OUT = 10L
    }

    /**
     * 获取ApiService
     */
    fun <S> getService(serviceClass: Class<S>, baseUrl: String): S {
        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
        return setRetrofitBuilder(retrofitBuilder).build().create(serviceClass)
    }

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     */
    abstract fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，Protocol
     */
    abstract fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder

    /**
     * 配置http
     */
    private val okHttpClient: OkHttpClient
        get() {
            return setHttpClientBuilder(OkHttpClient.Builder()).build()
        }

    protected val cookieJar by lazy {
        PersistentCookieJar(
            SetCookieCache(),
            SharedPrefsCookiePersistor(Utils.getApp())
        )
    }

    fun getCookie() = cookieJar
    fun clearCookie() = cookieJar.clear()
}